<?php
session_start();

class Users extends MY_Controller{
	private $status	= TRUE;
	private $token	= '';
	
	function __construct(){
		parent::__construct();
		$this->load->database();
		Sys::loadLanguage($this->params['lang'],'panel');
	}

	public function _remap($method, $params){
		$res = $this->checkAccessToken();
		
		$this->load->model('user_model');
		$info = $this->user_model->getInfoUser($this->params);
		$this->params['usr_info'] = $info['user'];
		
		if($res && $this->params['usr_info']['status']==1){
			$this->load->model('user_model');
			$info = $this->user_model->getInfoUser($this->params);
			$this->params['usr_info'] = $info['user'];		
			
			if($this->params['usr_info']['tipo']==='usuario' || $this->params['usr_info']['tipo']==='admin'){
				switch ($method) {
					case 'index':
							header('Location:'.Sys::$url_base.$this->params['lang_url'].'panel');
					break;
					//	ADMIN
					case 'edit_info':
							$this->user($method,$params);
					break;
					
					case 'update_info':
							$this->update($method,$params);
					break;
					default:
						show_404();
					break;
				}
			}else header('Location:'.Sys::$url_base.$this->params['lang_url'].'panel');
			
		}
		else if(isset($_COOKIE["p_goto"])){ //redireccionar a alguna url despues de logearse
			$url = $_COOKIE["p_goto"];
			setcookie('p_goto', '', time()-1200, '/');
			header("Location: ".$url);
		}else{
	    	header('Location:'.Sys::$url_base.$this->params['lang_url'].'');
		}
	}

	/**
	 * MUESTRA EL FORMULARIO MODIFICAR LA INFORMACION DEL USUARIO
	 * 
	 * @param $method			Metodo que llama la funcion
	 * @param $params			Parametros del Segmento de la URL u otros
	 */
	public function user($method = '', $params=''){
		
		//	CARGA LOS CSS
		$this->carabiner->css('dev/libs/superbox.css');
		$this->carabiner->css('dev/style.css');
		$this->carabiner->css('dev/panel/style.css');
		$this->carabiner->css('dev/panel/style_form.css');
		
		//	CARGA LOS JS
		$js	= array(
					array('dev/libs/jquery.js'),
					array('dev/libs/jquery.tools.min.js'),
					array('dev/panel/general.js'),
				);
		$this->carabiner->js($js);
		
		//	VARIABLE QUE SIRVE PARA INDICAR SI EXISTE ALGUN ERROR DE VALIDACION DE LOS PARAMETROS
		$show_error = FALSE;
		
		//	SI SE EDITA O ACTUALIZA LA INFORMACION DEL USUARIO
		if($method === 'edit_info' || $method === 'update_info'){
			
			$this->load->model('user_model');
			$info = $this->user_model->getInfoUser($this->params);
			$this->params['usr_info'] = $info['user'];
			// echo '<pre>';
			// var_dump($this->params);
			// echo '</pre>';
			
			$this->params['lang_txt_seccion'] = lang('txt_user_edit_info');
			
			$this->params['name']	= $this->params['usr_info']['nombre'];
			$this->params['email']	= $this->params['usr_info']['email'];
			$this->params['user']	=  $this->params['usr_info']['usuario'];
			$this->params['password']	= '';
			$this->params['confirm_password']	= '';
			
			// SI EXISTE ALGUN MENSAJE
			if (isset($params['msg_action'])){
				$this->params['class_msg']	= 'msg-ok';
				$this->params['msg_action']	= $params['msg_action'];
			}

			// INDICA EL MENU PADRE Y EL SUBMENU QUE SERAN SELECCIONADOS
			
			if($this->params['usr_info']['tipo']==='admin')
				$this->params['selected_menu5']	= 'mnu-selected';
			elseif($this->params['usr_info']['tipo']==='usuario')
				$this->params['selected_menu1']	= 'mnu-selected';
			
			$this->params['selected_submenu0']	= 'submnu-selected';

			// EN CASO DE CARGAR EL FORMULARIO SE TIENEN QUE INDICAR ESTOS PARAMETROS LOS CUALES SERAN PARTE DEL ACTION DEL FORMULARIO
			$this->params['controller'] 	= 'users/';
			$this->params['method'] 		= 'update_info/';
			$this->params['id']				= '';

			$this->params['seo'] = array(
				'title' 		=> ''.Sys::$title_web,
				'description' 	=> ''
			);
			
			// else{
				// $show_error = TRUE;
				// $this->params['msg'] = lang('txt_serie_active_id_update_error');
				// $this->params['seo'] = array(
					// 'title' 		=> ''.Sys::$title_web,
					// 'description' 	=> $this->params['msg']
				// );
			// }		
		}

		if($show_error){
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/errors/page_error", $this->params);
			$this->load->view("interface/panel/aside", $this->params);
			$this->load->view("interface/footer", $this->params);
		}
		else{			
			$this->params['aside_extra'] = $this->load->view('interface/panel/films/aside_buttons', $this->params, true);
			$this->load->view('interface/header',$this->params);
			$this->load->view('interface/panel/content',$this->params);
			$this->load->view('interface/panel/user/form_user_data',$this->params);
			
			if($this->params['usr_info']['tipo']==='admin')
				$this->load->view('interface/panel/aside',$this->params);
			elseif($this->params['usr_info']['tipo']==='usuario')
				$this->load->view('interface/panel/user/aside',$this->params);
			
			$this->load->view('interface/footer',$this->params);
		}
	}
	
	/**
	 *	GUARDA LA INFORMACION ENVIADA DEL FORMULARIO DE LA SERIE ACTIVA
	 * 
	 * 	@param string $method			METODO QUE LLAMA LA FUNCION
	 * @param array $params				Parametros del Segmento de la URL u otros
	 */
	public function update($method, $params=''){
		
		// VALIDA LOS PARAMETROS DEPENDIENDO QUE SE GUARDARA
		$response_errors = $this->validate('edit');
		
		// INDICA SI EXISTE ALGUN ERROR
		$show_error = FALSE;
		
		// SI NO EXISTE ERRORES EN LOS PARAMETROS VALIDADOS
		if($this->status == TRUE){
			// CARGA EL MODEL SERIE_ACTIVE_MODEL PARA GUARDAR LA SERIE ACTIVA
			$this->load->model('user_model');
			$user = $this->user_model->updateInfoUser($this->params);

			if($user!=FALSE)
				$this->user('update_info',array('msg_action'=>lang('txt_user_update_info_ok')));
			else{
				$show_error = TRUE;
				$this->params['msg'] = 'Error...';
				$this->params['seo'] = array(
					'title' 		=> ''.Sys::$title_web,
					'description' 	=> $this->params['msg']
				);
			}
		}else{
			// SI EXISTEN ERRORES DE VALIDACION DE LOS PARAMETROS
			$show_error = TRUE;
			$this->params['msg'] = implode(',', $response_errors);
			$this->params['seo'] = array(
				'title' 		=> ''.Sys::$title_web,
				'description' 	=> $this->params['msg']
			);
		}
		
		// SI EXISTE UN ERROR LO MUESTRA
		if($show_error){
			$this->carabiner->css('dev/style.css');
			$this->carabiner->css('dev/panel/style.css');
			
			$js	= array(
						array('dev/libs/jquery.js'),
						array('dev/panel/general.js')
					);
					
			$this->carabiner->js($js);
					
			$this->load->view("interface/header", $this->params);
			$this->load->view("interface/errors/page_error", $this->params);
			$this->load->view("interface/panel/aside", $this->params);
			$this->load->view("interface/footer", $this->params);
		}
	}
	
	/**
     * Permite incorporar las validaciones bases que apliquen para todos los servicios.
     * Validaciones mas espesificas tendran que ser en cada servicio en particular.
     * @author gama
     */
    protected function validate($val_method){
    	if(method_exists($this, 'validate_'.$val_method)){
    		$this->load->library('MY_Form_validation');
    		return $this->{'validate_'.$val_method}();
    	}
    }
	
	 private function validate_edit(){
    $validate = new MY_Form_validation();
    	$validate->setArrayValidate($this->params);
    	
    	$validate->set_rules(array(
    			array('field' => 'name', 
                     'label' => 'name', 
                     'rules' => 'required|max_length[50]'),
    			array('field' => 'email', 
                     'label' => 'email', 
                     'rules' => 'required|valid_email|max_length[70]'),
    			array('field' => 'password',
                     'label' => 'password', 
                     'rules' => 'min_length[6]|max_length[32]'),
    			array('field' => 'confirm_password', 
                     'label' => 'confirm_password', 
                     'rules' => 'max_length[32]'),
                     
				array('field' => 'user', 
                     'label' => 'user', 
                     'rules' => 'max_length[15]')
    	));
    	$this->status = $validate->run();
    	
    	if(isset($this->params["confirm_password"])){
    		if($this->params["confirm_password"] != $this->params["password"]){
    			$this->status = false;
    			$validate->_error_array['values'] = lang('txt_password_confirm');
    		}
    	}
    	
    	return $validate->_error_array;
    }
	
}